<template>
  <div>
    <page-dialog
      :title="title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <!-- 条件栏 -->
      <page-filter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
      </page-filter>
      <div class="select-resource-table">
        <div style="width: 50%">
          <p style="line-height: 24px" class="slip-edit">未选择资源</p>
          <dialog-table
            :refresh="tableInfo.refresh"
            :init-curpage="tableInfo.initCurpage"
            ref="resourceTable"
            v-model:ref-obj="tableInfo.ref"
            v-model:data="tableInfo.data"
            :listen-height="false"
            :pager="false"
            :query="filterInfo.query"
            :field-list="tableInfo.fieldList"
            :handle="tableInfo.handle"
            :highlight-row="highlightRow"
            :checkedList="tableInfo.checkedList"
            :checkedKey="tableInfo.checkedKey"
            :check-box="checkBox"
            @handleEvent="handleEvent"
          />
        </div>
        <div style="width: 48%">
          <p style="line-height: 24px" class="slip-edit">已选择资源</p>
          <dialog-table
            :init-curpage="cacheTableInfo.initCurpage"
            ref="cacheResourceTable"
            v-model:data="cacheTableInfo.data"
            :field-list="cacheTableInfo.fieldList"
            :handle="cacheTableInfo.handle"
            :listen-height="false"
            :check-box="false"
            :pager="false"
          />
        </div>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="selectResource">
import PageDialog from '@/components/PageDialog/index'
import DialogTable from '@/components/DialogTable/index'
import PageFilter from '@/components/PageFilter/index'
import { getDeptAll } from '@/api/core.js'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  showDialog: {
    type: Boolean,
  },
  api: {
    type: Function,
    default: getDeptAll,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  defaultList: {
    type: Array,
    default: function () {
      return []
    },
  },
  title: {
    type: String,
    default: '选择资源',
  },
  showKong: {
    type: Boolean,
    default: false,
  },
})

// 过滤相关配
const filterInfo = reactive({
  query: {
    sort: 'create_time desc',
    searchType: 'dept',
    keyword: '',
    ...props.query,
  },
  list: [
    {
      type: 'input',
      label: '名称/编码',
      value: 'keyword',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  ref: {},
  initCurpage: 1,
  data: [],
  checkedList: [],
  checkedKey: 'id',
  fieldList: [
    { label: '名称', value: 'name' },
    { label: '编码', value: 'code' },
  ],
})
const cacheTableInfo = reactive({
  refresh: 1,
  ref: {},
  initCurpage: 1,
  data: [],
  fieldList: [
    { label: '名称', value: 'name' },
    { label: '编码', value: 'code' },
  ],
  handle: {
    label: '操作',
    width: '100',
    btList: [
      {
        label: '删除',
        event: cacheRemove,
        show: true,
      },
    ],
  },
})
// 弹窗相关
const dialogInfo = reactive({
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      // disabled: true,
      disabled: false,
      event: save,
      show: true,
    },
  ],
})
const selectRow = ref(JSON.parse(JSON.stringify(props.defaultList)))
const tableInfoCopyData = ref([])
const copyCheckedList = ref([])

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emit('update:showDialog', newValue) // 更新父组件shows
  },
})
watch(
  () => tableInfo.data,
  (val) => {
    if (val.length) {
      toggleSelection(tableInfoCopyData.value)
    }
  }
)

onMounted(() => {
  proxy.$nextTick(() => {
    tableInfo.checkedList = props.defaultList
    getList()
  })
})

// 获取列表
function getList() {
  let api = props.api
  api(filterInfo.query).then((res) => {
    if (res && res.success) {
      if (props.showKong) {
        tableInfo.data.unshift({ id: -2, name: '空' })
      }
      tableInfo.data = res.data
      tableInfoCopyData.value = tableInfo.data
    }
  })
}
function search() {
  const search = filterInfo.query.keyword

  if (search) {
    tableInfo.data = tableInfoCopyData.value.filter((data) => {
      return Object.keys(data).some((key) => {
        if (key === 'name') {
          return String(data[key]).indexOf(search) > -1
        }
      })
    })
    tableInfo.checkedList = []
    tableInfo.data.forEach((item) => {
      if (copyCheckedList.value.includes(item.id)) {
        tableInfo.checkedList.push(item.id)
      }
    })
  } else {
    tableInfo.data = tableInfoCopyData.value
  }
  if (!search) {
    tableInfo.checkedList = copyCheckedList.value
  }
}

//删除
function cacheRemove(row, index) {
  let rows = cacheTableInfo.data
  rows.splice(index, 1)
  let rowArr = []
  rowArr.push(row)
  cancelCheck(rowArr)
  cacheTableInfo.data = rows
  selectRow.value = rows
  if (rows) {
    tableInfo.checkedList = rows.map(
      (item) => (tableInfo.checkedList[index] = item.id)
    )
  } else {
    tableInfo.checkedList = []
  }
}
function save() {
  selectRow.value = tableInfoCopyData.value.filter((item) =>
    copyCheckedList.value.includes(item.id)
  )
  if (selectRow.value && selectRow.value.length) {
    if (selectRow.value.length === tableInfoCopyData.value.length) {
      selectRow.value = [{ name: '全部', id: 0 }]
    }
    handleClose()
    emit('callback', selectRow.value)
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'selectCheck':
      selectRow.value = data
      cacheTableInfo.data = data
      break
    case 'tableCheck':
      selectRow.value = data
      cacheTableInfo.data = data
      if (tableInfo.data.length === tableInfoCopyData.value.length) {
        copyCheckedList.value = data.map((item) => item.id)
      } else {
        let tableIds = tableInfo.data.map((item) => item.id)
        let tableNot = copyCheckedList.value.filter(
          (item) => !tableIds.includes(item)
        )

        copyCheckedList.value = tableNot.concat(data.map((item) => item.id))
      }
      break
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emit('reset')
}
//删除时取消勾选
function cancelCheck(val) {
  if (val.length) {
    proxy.$nextTick(() => {
      val.forEach((row) =>
        proxy.$refs['resourceTable'].toggleRowSelection(row, false)
      )
    })
  }
}
function toggleSelection(val) {
  if (tableInfo.checkedList[0] === 0) {
    tableInfo.checkedList = tableInfo.data.map((item) => item.id)
  }
  cacheTableInfo.data = []
  let rows =
    val.filter(
      (row) =>
        tableInfo.checkedList.includes(row[tableInfo.checkedKey]) ||
        row.disabled
    ) || []
  if (rows.length) {
    proxy.$nextTick(() => {
      rows.forEach((row) =>
        proxy.$refs['resourceTable'].toggleRowSelection(row, true)
      )
    })
  }
  cacheTableInfo.data = rows
}
</script>

<style scoped lang="scss">
.page-table {
  width: 48%;
  height: 400px;
  .el-dialog__body {
    display: flex;
    flex-direction: column;
  }
}
.el-table--border {
  border-bottom: 1px solid #ebeef5;
}
.select-resource-table {
  display: flex;
  flex-flow: row;
  justify-content: space-between;
  // overflow: hidden;
  height: 400px;
}
</style>
